package com.fbd.remote;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fbd.internalcommon.dto.DirectionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class MapDirectionClient {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${map.key}")
    String mapKey;
    public DirectionResponse direction(String depLongitude, String depLatitude, String destLongitude, String destLatitude){
        /*&key=e2ae1f9ff6708a6d5ae63a777811692b*/
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append("https://restapi.amap.com/v3/direction/driving");
        urlBuilder.append("?");
        urlBuilder.append("origin=" + depLongitude + "," + depLatitude);
        urlBuilder.append("&");
        urlBuilder.append("destination=" + destLongitude + "," + destLatitude);
        urlBuilder.append("&extensions=base&output=json&");
        urlBuilder.append("key=" + mapKey);

        System.out.println(urlBuilder.toString());

        ResponseEntity<String> forEntity = restTemplate.getForEntity(urlBuilder.toString(), String.class);
        String body = forEntity.getBody();
        DirectionResponse directionResponse = parseDirectionEntity(body);
        return directionResponse;
    }

    private DirectionResponse parseDirectionEntity(String directionString){
        DirectionResponse directionResponse = null;
        try {
            directionResponse = new DirectionResponse();
            JSONObject result = JSONObject.parseObject(directionString);
            String status = result.getString("status");
            if ("1".equals(status) ){
                String route = result.getString("route");
                if (route != null){
                    JSONObject jsonObject = JSONObject.parseObject(route);
                    JSONArray paths = jsonObject.getJSONArray("paths");
                    JSONObject jsonObject1 = paths.getJSONObject(0);
                    Integer distance = jsonObject1.getInteger("distance");
                    Integer duration = jsonObject1.getInteger("duration");
                    directionResponse.setDistance(distance);
                    directionResponse.setDuration(duration);
                }
            }
        }catch (Exception e){

        }
        return directionResponse;
    }
}
